<template>
  <div>
    <el-form :inline="true" :model="catagorys">
      <el-form-item label="一级分类">
        <el-select
          v-model="catagorys.c1"
          placeholder="一级分类"
          style="width: 240px"
          clearable
          @change="c1Change"
          :disabled="disabled"
        >
          <el-option
            v-for="item in c1List"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          v-model="catagorys.c2"
          placeholder="二级分类"
          style="width: 240px"
          clearable
          @change="c2Change"
          :disabled="disabled"
        >
          <el-option
            v-for="item in c2List"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select
          v-model="catagorys.c3"
          placeholder="三级分类"
          style="width: 240px"
          clearable
          @change="c3Change"
          :disabled="disabled"
        >
          <el-option
            v-for="item in c3List"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { reqAttrList, rqaAttrNameList } from '@/api/product/attr'
import type { AttrData } from '@/api/product/attr/types'
import { tr } from 'element-plus/es/locales.mjs'
const catagorys = reactive<{
  c1?: number
  c2?: number
  c3?: number
}>({})
const disabled = ref(false)
const c1List = ref<AttrData[]>([])
const c2List = ref<AttrData[]>([])
const c3List = ref<AttrData[]>([])
onMounted(async () => {
  let { data } = await reqAttrList(0)
  c1List.value = data
})
const c1Change = async (value: number) => {
  // 清除 v-model 标签已填、选的值
  delete catagorys.c2
  delete catagorys.c3
  if (value) {
    let { data } = await reqAttrList(value)
    c2List.value = data
    emit('c1Change', value)
  } else {
    emit('c1Change')
  }
  emit('c2Change')
  emit('c3Change')
}
const c2Change = async (value: number) => {
  catagorys.c2 = value
  // 清除 v-model 标签已填、选的值
  delete catagorys.c3
  if (value) {
    let { data } = await reqAttrList(value)
    c3List.value = data
    emit('c2Change', value)
  } else {
    emit('c2Change')
  }
  emit('c3Change')
}
const c3Change = (value: number) => {
  catagorys.c3 = value
  emit('c3Change', value)
}
function disableAll() {
  disabled.value = true
}
function enableAll() {
  disabled.value = false
}
// 自定义事件，用于子组件 --> 父组件
const emit = defineEmits(['c1Change', 'c2Change', 'c3Change'])
// 暴露一些函数，用于父组件  --> 子组件
defineExpose({ disableAll, enableAll })
</script>
<script lang="ts">
export default {
  name: 'Catagory',
}
</script>

<style scoped></style>
